package iip

import (
    "path/filepath"

    "github.com/gin-gonic/gin"
    "go.uber.org/zap"
    "gorm.io/gorm"
    "iip/dictionary"
    "iip/idgen"
    "iip/webserver"
    "libgo/network/gins/ginsession"
    "libgo/security/TLS"
    "libgo/storage/db_config"
    "libgo/utils"
    "rpc"
)



type IIP struct {
    cfg    *Config
    l      *zap.Logger
    logger *zap.SugaredLogger
    db     *gorm.DB

    idgen *idgen.IDGen
    dbcfg *db_config.DBConfig
    dict  *dictionary.Dictionary

    r  *gin.Engine
    ss *ginsession.RediSessiontore
}

func New() *IIP {
    x := &IIP{}
    return x
}

func (s *IIP) WithLogger(l *zap.Logger) *IIP {
    s.l = l.With(zap.String("mod", "TMS"))
    s.logger = s.l.Sugar()
    return s
}

func (s *IIP) WithConfig(cfg *Config) *IIP {
    s.cfg = cfg
    return s
}

func (s *IIP) WithDB(db *gorm.DB) *IIP {
    s.db = db
    return s
}

func (s *IIP) WithDBConfig(c *db_config.DBConfig) *IIP {
    s.dbcfg = c
    return s
}

func (s *IIP) WithIDGen(idgen *idgen.IDGen) *IIP {
    s.idgen = idgen
    return s
}

func (s *IIP) WithWebServer(srv *webserver.WebServer) *IIP {
    s.r = srv.GinEngine()
    s.ss = srv.SessionStore()
    return s
}

func (s *IIP) WithDictionary(d *dictionary.Dictionary) *IIP {
    s.dict = d
    return s
}

func (s *IIP) Start() {

    s._start_db()

    s._start_webserver()

    s._start_grpc()
}

func (s *IIP) _start_db() {









}

func (s *IIP) _start_webserver() {


    s.r.GET("/api/v1/weight_record", s.WeightRecordPagedList)
    s.r.GET("/api/v1/weight_record/:id", s.WeightRecordByID)
}

func (s *IIP) _start_grpc() {
    ca := filepath.Join(utils.ProjectRoot(), s.cfg.CA)
    cert := filepath.Join(utils.ProjectRoot(), s.cfg.Cert)
    key := filepath.Join(utils.ProjectRoot(), s.cfg.Key)
    for _, f := range []string{ca, cert, key} {
        if !utils.IsFileExists(f) {
            s.logger.Error(f, "not exit")
            return
        }
    }

    tls_cfg := TLS.NewTCPServer().WithRootCertificate(ca).WithServerCertificate(cert, key).TLSConfig()
    if err := rpc.NewTMSServer(s.cfg.RPCAddr, s.cfg.RPCPort, tls_cfg, s); err != nil {
        s.logger.Error(err)
    } else {
        s.logger.Infof("启动GRPC服务%s:%d 成功", s.cfg.RPCAddr, s.cfg.RPCPort)
    }
}

func (s *IIP) Close() {

}
